import React, { useState, useCallback, useMemo } from 'react';
import {
  Card,
  Tabs,
  Button,
  Space,
  Spin,
  Divider,
  Switch,
  Tooltip,
  Row,
  Col,
  Statistic,
  Badge,
  message
} from 'antd';
import {
  BugOutlined,
  ExperimentOutlined,
  BarChartOutlined,
  PlayCircleOutlined,
  ReloadOutlined,
  CheckCircleOutlined,
  InfoCircleOutlined,
  ThunderboltOutlined
} from '@ant-design/icons';
import { 
  UnifiedAnalysisRequest, 
  UnifiedAnalysisResult, 
  CompatibilityIssue, 
  AnalysisConfig 
} from '../../types/analysis';
import ProblemList from './ProblemList';
import OptimizationView from './OptimizationView';
import './UnifiedAnalysisPanel.css';

interface UnifiedAnalysisPanelProps {
  sqlContent: string;
  sourceDbType: string;
  targetDbType: string;
  userId: number;
  aiEnhancementEnabled?: boolean; // 新增：从父组件传递AI增强选项
  onAnalysisRequest?: (request: UnifiedAnalysisRequest) => Promise<UnifiedAnalysisResult>;
  onIssueClick?: (issue: CompatibilityIssue) => void;
  onOptimizedSqlApply?: (sql: string) => void;
  config?: Partial<AnalysisConfig>;
}

const UnifiedAnalysisPanel: React.FC<UnifiedAnalysisPanelProps> = ({
  sqlContent,
  sourceDbType,
  targetDbType,
  userId,
  aiEnhancementEnabled = false, // 默认值
  onAnalysisRequest,
  onIssueClick,
  onOptimizedSqlApply,
  config = {}
}) => {
  const [isAnalyzing, setIsAnalyzing] = useState(false);
  const [analysisResult, setAnalysisResult] = useState<UnifiedAnalysisResult | null>(null);
  const [activeTab, setActiveTab] = useState('analysis');
  const [autoAnalysis, setAutoAnalysis] = useState(config.enableRealTimeAnalysis ?? true);
  const [showOptimization, setShowOptimization] = useState(false);
  const [aiEnhanced, setAiEnhanced] = useState(aiEnhancementEnabled);

  // 默认配置
  const analysisConfig: AnalysisConfig = {
    enableRealTimeAnalysis: true,
    enableAutoOptimization: false,
    debounceDelay: 1500,
    maxResults: 100,
    showLineNumbers: true,
    highlightIssues: true,
    ...config
  };

  // 执行分析
  const performAnalysis = useCallback(async (useAiEnhancement?: boolean) => {
    const currentAiEnabled = useAiEnhancement !== undefined ? useAiEnhancement : aiEnhanced;
    
    if (!sqlContent.trim()) {
      message.warning('请输入SQL语句');
      return;
    }

    if (!onAnalysisRequest) {
      message.error('分析服务不可用');
      return;
    }

    setIsAnalyzing(true);
    try {
      const request: UnifiedAnalysisRequest = {
        sqlContent,
        sourceDbType,
        targetDbType,
        aiEnhancementEnabled: currentAiEnabled,
        userId,
        taskName: `Manual-Analysis-${Date.now()}`
      };

      const result = await onAnalysisRequest(request);
      
      if (result.success) {
        setAnalysisResult(result);
        setShowOptimization(currentAiEnabled && !!result.optimizedSql);
        
        const issueCount = result.statistics.totalIssues;
        if (issueCount === 0) {
          message.success('分析完成，未发现兼容性问题');
        } else {
          message.success(`分析完成，发现 ${issueCount} 个兼容性问题`);
        }
      } else {
        setAnalysisResult(null);
        message.error(result.errorMessage || '分析失败');
      }
    } catch (error: any) {
      console.error('分析失败:', error);
      message.error(error.message || '分析失败，请检查网络连接');
      setAnalysisResult(null);
    } finally {
      setIsAnalyzing(false);
    }
  }, [sqlContent, sourceDbType, targetDbType, aiEnhanced, userId, onAnalysisRequest]);

  // 处理问题点击
  const handleIssueClick = useCallback((issue: CompatibilityIssue) => {
    if (onIssueClick) {
      onIssueClick(issue);
    }
  }, [onIssueClick]);

  // 处理优化SQL应用
  const handleOptimizedSqlApply = useCallback((sql: string) => {
    if (onOptimizedSqlApply) {
      onOptimizedSqlApply(sql);
      message.success('已应用优化后的SQL');
    }
  }, [onOptimizedSqlApply]);

  // 计算统计数据
  const statistics = useMemo(() => {
    if (!analysisResult) {
      return {
        totalIssues: 0,
        highCount: 0,
        mediumCount: 0,
        lowCount: 0,
        infoCount: 0
      };
    }

    const stats = analysisResult.statistics;
    return {
      totalIssues: stats.totalIssues,
      highCount: stats.highSeverityCount,
      mediumCount: stats.mediumSeverityCount,
      lowCount: stats.lowSeverityCount,
      infoCount: stats.infoCount || 0
    };
  }, [analysisResult]);

  // 渲染控制面板
  const renderControlPanel = () => (
    <Card size="small" style={{ marginBottom: 16 }}>
      <Space style={{ width: '100%', justifyContent: 'space-between' }}>
        <Space>
          <Button
            type="primary"
            icon={<PlayCircleOutlined />}
            onClick={() => performAnalysis()}
            loading={isAnalyzing}
            disabled={!sqlContent.trim()}
          >
            {isAnalyzing ? '分析中...' : '开始分析'}
          </Button>
          
          <Button
            icon={<ReloadOutlined />}
            onClick={() => performAnalysis()}
            disabled={isAnalyzing || !analysisResult}
            size="small"
          >
            重新分析
          </Button>
        </Space>
        
        <Space>
          <Tooltip title="启用AI增强分析">
            <Switch
              checked={aiEnhanced}
              onChange={setAiEnhanced}
              size="small"
              checkedChildren="AI增强"
              unCheckedChildren="规则分析"
            />
          </Tooltip>
          
          <Tooltip title="启用实时分析">
            <Switch
              checked={autoAnalysis}
              onChange={setAutoAnalysis}
              size="small"
              checkedChildren="自动"
              unCheckedChildren="手动"
            />
          </Tooltip>
        </Space>
      </Space>
    </Card>
  );

  // 渲染统计卡片
  const renderStatistics = () => {
    if (!analysisResult) return null;

    return (
      <Card size="small" title="分析结果" style={{ marginBottom: 16 }}>
        <Row gutter={[8, 8]}>
          <Col span={12}>
            <Statistic 
              title="SQL语句" 
              value={analysisResult.statistics.totalStatements}
              prefix={<BarChartOutlined />}
              valueStyle={{ fontSize: 16, color: '#1890ff' }}
            />
          </Col>
          <Col span={12}>
            <Statistic 
              title="问题总数" 
              value={statistics.totalIssues}
              prefix={statistics.totalIssues > 0 ? <BugOutlined /> : <CheckCircleOutlined />}
              valueStyle={{ 
                fontSize: 16, 
                color: statistics.totalIssues > 0 ? '#ff4d4f' : '#52c41a' 
              }}
            />
          </Col>
        </Row>
        
        {statistics.totalIssues > 0 && (
          <>
            <Divider style={{ margin: '12px 0' }} />
            <Row gutter={[4, 4]}>
              <Col span={6}>
                <div style={{ textAlign: 'center' }}>
                  <div style={{ color: '#ff4d4f', fontWeight: 'bold' }}>
                    {statistics.highCount}
                  </div>
                  <div style={{ fontSize: 11, color: '#666' }}>高危</div>
                </div>
              </Col>
              <Col span={6}>
                <div style={{ textAlign: 'center' }}>
                  <div style={{ color: '#faad14', fontWeight: 'bold' }}>
                    {statistics.mediumCount}
                  </div>
                  <div style={{ fontSize: 11, color: '#666' }}>中危</div>
                </div>
              </Col>
              <Col span={6}>
                <div style={{ textAlign: 'center' }}>
                  <div style={{ color: '#1890ff', fontWeight: 'bold' }}>
                    {statistics.lowCount}
                  </div>
                  <div style={{ fontSize: 11, color: '#666' }}>低危</div>
                </div>
              </Col>
              <Col span={6}>
                <div style={{ textAlign: 'center' }}>
                  <div style={{ color: '#52c41a', fontWeight: 'bold' }}>
                    {statistics.infoCount}
                  </div>
                  <div style={{ fontSize: 11, color: '#666' }}>提示</div>
                </div>
              </Col>
            </Row>
          </>
        )}
        
        {analysisResult.metadata && (
          <>
            <Divider style={{ margin: '12px 0' }} />
            <div style={{ fontSize: 11, color: '#999' }}>
              分析时间: {analysisResult.statistics.processingTimeMs}ms
              {analysisResult.metadata.modelName && (
                <> | 模型: {analysisResult.metadata.modelName}</>
              )}
            </div>
          </>
        )}
      </Card>
    );
  };

  // 渲染主要内容
  const renderContent = () => {
    if (isAnalyzing) {
      return (
        <Card>
          <div style={{ textAlign: 'center', padding: '40px 0' }}>
            <Spin size="large" />
            <div style={{ marginTop: 16 }}>
              正在进行{aiEnhanced ? 'AI增强' : '规则'}分析...
            </div>
            {aiEnhanced && (
              <div style={{ marginTop: 8, fontSize: 12, color: '#666' }}>
                AI增强分析可能需要较长时间，请耐心等待
              </div>
            )}
          </div>
        </Card>
      );
    }

    if (!analysisResult) {
      return (
        <Card>
          <div style={{ textAlign: 'center', padding: '40px 0', color: '#999' }}>
            <InfoCircleOutlined style={{ fontSize: 48, marginBottom: 16 }} />
            <div>请输入SQL语句并选择分析选项</div>
            <div style={{ fontSize: 12, marginTop: 8 }}>
              支持{aiEnhanced ? 'AI增强' : '规则'}分析模式
            </div>
          </div>
        </Card>
      );
    }

    const tabItems = [
      {
        key: 'analysis',
        label: (
          <Space>
            <BugOutlined />
            问题列表
            {statistics.totalIssues > 0 && (
              <Badge count={statistics.totalIssues} size="small" />
            )}
          </Space>
        ),
        children: (
          <ProblemList
            issues={analysisResult.issues}
            onIssueClick={handleIssueClick}
            analysisSource={aiEnhanced ? 'LLM' : 'RULE'}
            showLineNumbers={analysisConfig.showLineNumbers}
          />
        )
      }
    ];

    // 如果启用了AI增强且有优化结果，添加优化标签页
    if (aiEnhanced && showOptimization && analysisResult.optimizedSql) {
      tabItems.push({
        key: 'optimization',
        label: (
          <Space>
            <ThunderboltOutlined />
            SQL优化
            <Badge dot color="green" />
          </Space>
        ),
        children: (
          <OptimizationView
            originalSql={sqlContent}
            optimizedSql={analysisResult.optimizedSql}
            explanation={analysisResult.optimizationExplanation}
            optimizations={analysisResult.optimizations || []}
            onApplyOptimization={handleOptimizedSqlApply}
          />
        )
      });
    }

    return (
      <Tabs
        activeKey={activeTab}
        onChange={setActiveTab}
        items={tabItems}
        size="small"
      />
    );
  };

  return (
    <div className="unified-analysis-panel">
      {renderControlPanel()}
      {renderStatistics()}
      
      <Card 
        title={
          <Space>
            {aiEnhanced ? <ExperimentOutlined /> : <BugOutlined />}
            分析结果
            {analysisResult && (
              <Badge 
                count={statistics.totalIssues} 
                color={statistics.totalIssues > 0 ? '#ff4d4f' : '#52c41a'}
              />
            )}
          </Space>
        }
        style={{ flex: 1 }}
      >
        {renderContent()}
      </Card>
    </div>
  );
};

export default UnifiedAnalysisPanel;